<template>
    <div>
        <Card>
            <Row class="form-row">
                <Form :model="filters" ref="form1" label-position="right" :label-width="90" inline>
                    <FormItem label="小区名称">
                        <div class="filters-input">
                            <el-select v-model="filters.housingId" :clearable="true" placeholder="请选择小区">
                                <el-option v-for="item in houseList" :value="item.id" :key="item.id" :label="item.name">
                                </el-option>
                            </el-select>
                        </div>
                    </FormItem>
                    <!-- <FormItem label="优惠券名称">
                        <Input v-model="filters.name" placeholder="优惠券名称" style="width: 250px"></Input>
                    </FormItem>-->
                    <!-- <FormItem label="生效日期">
                        <DatePicker type="date" format="yyyy-MM-dd" placeholder="生效日期" v-model="filters.beginTime" style="width: 250px"></DatePicker>
                    </FormItem>
                    <FormItem label="截止日期">
                        <DatePicker type="date" format="yyyy-MM-dd" placeholder="截止日期" v-model="filters.endTime" style="width: 250px"></DatePicker>
                    </FormItem> -->
                    <FormItem>
                        <Button type="primary" icon="ios-search" @click="handleQuery('form1')">
                            搜索
                        </Button>
                    </FormItem>
                </Form>
            </Row>
            <Row class="form-row">
                <Button type="primary" icon="md-add" @click="handleAdd()" style="margin-right: 10px;">新增</Button>
            </Row>

            <el-table stripe border :loading="tableLoading" :data="tableData" ref="table" style="width: 100%">
                <template slot="empty">暂无数据</template>
                <el-table-column prop="houseName" label="小区名称"></el-table-column>
                <el-table-column prop="name" label="优惠券名称"></el-table-column>
                <el-table-column prop="number" label="优惠券编号"></el-table-column>
                <el-table-column prop="remark" label="优惠券说明"></el-table-column>
                <el-table-column prop="url" label="优惠券领取地址"></el-table-column>
                <el-table-column prop="beginTime" label="生效日期"></el-table-column>
                <el-table-column prop="endTime" label="截至日期"></el-table-column>
                <el-table-column label="状态" align="center" width="180">
                    <!-- 数据库1是启用，-1是禁用 -->
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.status" active-text="开启" inactive-text="禁用"
                                   @change="switchChange(scope.$index, scope.row)"
                                   :change="logchange(scope.$index, scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="handleAdd(scope.row.id)">修改</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                    <!--<template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="primary"
                            @click="handleAdd(scope.row.id)">修改
                        </el-button>
                        <Poptip confirm title="确定删除?" transfer @on-ok="handleDelete(scope.row.id)"
                                style="margin-right:5px;">
                            <el-button
                                size="mini"
                                type="danger">删除
                            </el-button>
                        </Poptip>
                    </template>-->
                </el-table-column>
            </el-table>

            <Page style="margin: 10px 0;" :total="pageTotal" :current="pageNum" :page-size="pageSize" show-total
                  show-sizer show-elevator @on-change="handlePage" @on-page-size-change='handlePageSize'>
            </Page>
        </Card>

        <Modal v-model="formVisible" :title="modal && modal.id ? '修改' : '新增'" class="modal-content" width="900"
               :mask-closable="false">
            <Form :model="modal" :rules="rule" ref="form2" label-position="right" :label-width="110" class="myOpenFrom">
                <FormItem label="小区" prop="housingId">
                    <Select v-model="modal.housingId" :clearable="true">
                        <Option v-for="item in modalhouseList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="优惠券名称" prop="name">
                    <Input v-model="modal.name" placeholder="优惠券名称"></Input>
                </FormItem>
                <FormItem label="优惠券编号" prop="number">
                    <Input v-model="modal.number" placeholder="优惠券编号"></Input>
                </FormItem>
                <FormItem label="优惠券说明" prop="remark">
                    <Input v-model="modal.remark" placeholder="优惠券说明"></Input>
                </FormItem>
                <FormItem label="领券地址" prop="url">
                    <Input v-model="modal.url" placeholder="领券地址"></Input>
                </FormItem>
                <FormItem label="生效日期" prop="beginTime">
                    <DatePicker type="date" format="yyyy-MM-dd" placeholder="生效日期" v-model="modal.beginTime"
                                style="width: 100%"></DatePicker>
                </FormItem>
                <FormItem label="截止日期" prop="endTime">
                    <DatePicker type="date" format="yyyy-MM-dd" placeholder="截止日期" v-model="modal.endTime"
                                style="width: 100%"></DatePicker>
                </FormItem>
                <FormItem label="优惠券图片">
                    <el-upload @click.native=couponPicName(modal.name)
                               accept="image/jpeg,image/jpg,image/png"
                               ref="upload"
                               class="avatar-uploader"
                               :headers="{'x-access-token':token}"
                               :action="act"
                               :show-file-list="false"
                               :disabled="disabledTwo"
                               :data="couponPicUrl"
                               :on-success="handleAvatarSuccess"
                               :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar-twoImg">
                        <i v-else class="el-icon-plus avatar-uploader-icon-twoImg"></i>
                    </el-upload>
                    <p>建议尺寸为312 X 87px,支持jpg,png,jpeg格式</p>
                    <input type="hidden" name="couponPic" v-model="modal.couponPic"/>
                </FormItem>
            </Form>

            <div slot="footer">
                <Button type="text" size="large" @click="onCancel">取消</Button>
                <Button type="primary" size="large" @click="handleSubmit" :loading="formLoading">确定</Button>
            </div>

        </Modal>
    </div>
</template>


<script>
    import baseURL from '_conf/url'
    import QRCode from 'qrcodejs2'
    import Treeselect from "@riophae/vue-treeselect";
    import Cookies from 'js-cookie'
    import {TOKEN_KEY} from '@/libs/util'

    const token = Cookies.get(TOKEN_KEY)
    const act = baseURL + "/common/uploadImg"
    //校验规则
    const rules = {
        housingId: [
            {
                required: true,
                message: "请选择小区",
            }
        ],
        name: [
            {
                required: true,
                message: "请输入优惠券名称",
                trigger: "blur"
            }
        ],
        number: [
            {
                required: true,
                message: "请输入优惠券编号",
                trigger: "blur"
            }
        ],
        url: [
            {
                required: true,
                message: "请输入领券地址",
                trigger: "blur"
            }
        ],
        remark: [
            {
                required: true,
                message: "请输入优惠券说明",
                trigger: "blur"
            }
        ],
        beginTime: [
            {
                required: true,
                message: "请选择生效日期",
            }
        ],
        endTime: [
            {
                required: true,
                message: "请选择截止日期",
            }
        ],
    };

    //加载数据
    let loadData = function () {
        if (this.tableLoading) return;
        this.tableLoading = true;
        let params = this.filters;
        params.pageNum = this.pageNum;
        params.pageSize = this.pageSize;
        console.log(params);
        //与后台交换数据
        this.postRequest("/api/couponOhter/loadData", params).then(res => {
            console.log(res);
            this.tableLoading = false;
            if (res.code == 20000) {
                this.tableData = res.data.list;
                this.pageTotal = res.data.total;
            } else {
                this.tableData = [];
                this.$Message.error({
                    content: res.message,
                    duration: 5
                });
            }
        });
    };
    //查询
    let handleQuery = function (name) {
        this.filters.pageNum = 1;
        this.loadData();
    };

    //删除
    let handleDelete = function (id) {
        this.getRequest("/api/couponOhter/deleteById?id=" + id).then(res => {
            this.tableLoading = false;
            if (res.code == 20000) {
                this.$Message.success({
                    content: "删除成功",
                    duration: 5
                });
                this.pageNum = 1;
                this.loadData();
            } else {
                this.$Message.error({
                    content: res.message,
                    duration: 5
                });
            }
        });
    };
    //打开页面
    let handleAdd = function (id) {
        this.modal = {};
        this.imageUrl = "";
        this.formVisible = true;
        let url = "/api/couponOhter/openModel";
        if (id) {
            url = "/api/couponOhter/openModel?id=" + id;
            this.getRequest(url).then(res => {
                console.log(res)
                this.tableLoading = false;
                if (res.code == 20000) {
                    this.modal = res.data.couponOtherCustom
                    this.imageUrl = res.data.couponOtherCustom.couponPic;
                } else {
                    this.$Message.error({
                        content: res.message,
                        duration: 5
                    });
                }
            });
        }
    };
    //保存
    let save = function () {
        let parms = this.modal;
        if (this.modal.beginTime >= this.modal.endTime) {
            this.$Message.warning('生效时间不能大于等于截止时间！');
            this.formLoading = false;
        } else {
            parms.beginTime = (this.modal.beginTime).toLocaleDateString();
            parms.endTime = (this.modal.endTime).toLocaleDateString();
            console.log(parms.beginTime)
            this.postRequest("/api/couponOhter/saveOrUpdate", parms).then(res => {
                this.tableLoading = false;
                console.log(res)
                if (res.code == 20000) {
                    this.formLoading = false;
                    this.formVisible = false;
                    this.$Message.success({
                        content: "保存成功！",
                        duration: 5
                    });
                    this.onCancel();
                    this.loadData();
                } else {
                    this.formLoading = false;
                    this.$Message.error({
                        content: res.message,
                        duration: 5
                    });
                }
            });
        }
    };
    //保存
    let handleSubmit = function () {
        this.$refs["form2"].validate(valid => {
            if (valid) {
                this.formLoading = true;
                this.save();
            }
        });
    };
    //小区变化
    let typeIntchange = function (value) {
        console.log("选中了" + value);
        if (value == 1) {
            this.houseshow = 1;
        } else if (value == 2) {
            this.houseshow = 2;
        }
    }
    //filter里面的
    let onCancel = function () {
        this.$refs.upload.clearFiles();
        this.$refs["form2"].resetFields();
        this.formLoading = false;
        this.formVisible = false;
        this.houseshow = 0;
    };
    //formCode
    let cancelCode = function () {
        document.getElementById('qrcode').innerHTML = '';
        this.formCode = false;
    };

    export default {
        name: "userList",
        components: {
            Treeselect
        },
        data() {
            return {
                houseshow: 0,
                date: '',
                data1: {},
                fileList: [],
                loadingStatus: false,
                housingId: null,
                houseList: [],//小区
                filehouseList: [],
                //filter里面的
                modalhouseList: [],
                name: "",
                //查询条件
                filters: {},
                //页码
                pageNum: 1,
                //每页数量
                pageSize: 10,
                //总数
                pageTotal: 0,
                //验证规则
                rule: rules,
                token: token,
                act: act,
                //表格数据
                tableData: [],
                //数据表格隐藏那个状态
                tableLoading: false,
                //对话框隐藏状态
                formVisible: false,
                formCode: false,
                //表单提交状态
                formLoading: false,
                modal: {},
                //图片
                imageUrl: '',
                disabledTwo: true,
                couponPicUrl: {},
            };
        },
        created: function () {
            this.gethouse();
            this.loadData();
        },
        methods: {
            //filter里面的
            typeIntchange,
            loadData,
            save,
            handleQuery,
            cancelCode,
            handleDelete,
            handlePage(value) {
                this.pageNum = value;
                this.loadData();
            },
            handlePageSize(value) {
                this.pageSize = value;
                this.loadData();
            },
            handleAdd,
            handleSubmit,
            onCancel,
            gethouse() {
                let url = "/api/housing/getHousingByLogin";
                this.postRequest(url).then(res => {
                    console.log(res);
                    this.houseList = res;
                    this.modalhouseList = res;
                });
            },
            //图片
            couponPicName: function (name) {
                if (!name) {
                    this.disabledTwo = true;
                    this.$Message.warning('请先输入优惠券名称！');
                    return
                } else {
                    this.couponPicUrl = {
                        name: name + "_couponPic"
                    }
                    this.disabledTwo = false;
                    console.log(this.couponPicUrl);
                }
            },
            handleAvatarSuccess(res, file) {
                this.modal.couponPic = res;
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload(file) {
                const isSize = new Promise(function (resolve, reject) {

                    let _URL = window.URL || window.webkitURL;
                    let img = new Image();
                    img.onload = function () {
                        let valid = img.width <= 312 && img.height <= 87;
                        valid ? resolve() : reject();
                    }
                    img.src = _URL.createObjectURL(file);
                }).then(() => {
                    return file;
                }, () => {
                    this.$Message.info({
                        content: '图片长宽不能大于312X87',
                        duration: 5,
                        closable: true
                    });
                    return Promise.reject();
                });
                return isSize
            },
            //开启券
            switchChange: function (index, row) {
                console.log(row)
                let status
                if (row.status) {
                    status = 1;
                } else {
                    status = 0;
                }
                let params = {};
                params.id = row.id;
                // params.status = status;
                console.log(params);
                this.postRequest("/api/couponOhter/useCoupon", params).then(res => {
                    if (res.code == 20000) {
                        console.log(res)
                        this.loadData();
                        // this.$Message.success("修改成功！");
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },
            logchange: function (index, row) {
                if (row.status == 1) {
                    row.status = true;
                } else if (row.state == "0") {
                    row.status = false;
                }
            }

        }
    };
</script>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon-oneImg {
        font-size: 28px;
        color: #8c939d;
        /*width: 178px;*/
        /*height: 178px;*/
        width: 250px;
        height: 120px;
        line-height: 120px;
        text-align: center;
    }

    .avatar-oneImg {
        width: 250px;
        height: 120px;
        display: block;
    }

    .avatar-uploader-icon-twoImg {
        font-size: 28px;
        color: #8c939d;
        width: 316px;
        height: 160px;
        line-height: 160px;
        text-align: center;
    }

    avatar-twoImg {
        width: 108px;
        height: 30px;
        display: block;
    }

    .avatar-uploader-icon-threeImg {
        font-size: 28px;
        color: #8c939d;
        width: 90px;
        height: 90px;
        line-height: 90px;
        text-align: center;
    }

    avatar-threeImg {
        width: 90px;
        height: 90px;
        display: block;
    }


</style>
